package cc.sheji.Service;
import cc.sheji.domain.*;
import cc.sheji.reposity.NoticeRepository;
import cc.sheji.util.QueryHelp;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.PathVariable;

import java.util.List;


@Service
public class NoticeService {

    @Autowired
    NoticeRepository noticeRepository;

    public Notice create(Notice entity) {

        entity.setId(null);
        entity=noticeRepository.save(entity);
        return entity;

    }

    public Notice get(@PathVariable("id") Long id) {

        Notice entity = noticeRepository.findById(id).get();
        return entity;
    }

    public List<Notice> list(NoticeQueryCriteria criteria, Pageable pageable) {
        System.out.println(criteria);
        Sort order = Sort.by(Sort.Direction.DESC, "createTime");
        pageable = PageRequest.of(pageable.getPageNumber(), pageable.getPageSize(), order);
        Page<Notice> page = noticeRepository.findAll((root, criteriaQuery, criteriaBuilder) ->
                QueryHelp.getPredicate(root, criteria, criteriaBuilder), pageable);
        return page.getContent();
    }

    public Notice update(Notice entity) {
        return noticeRepository.save(entity);
    }


    public boolean delete(Long id) {

        Notice ad = noticeRepository.findById(id).get();
        ad.setDeleted(1);
        noticeRepository.save(ad);
        return true;
    }
}
